import { ADD_TASK, DEL_TASK } from "./actionTypes";

let nextId = 4;

const defaultState = {
  tasks: [
    { id: 1, text: "吃饭", done: true },
    { id: 2, text: "睡觉", done: true },
    { id: 3, text: "打豆豆", done: false },
  ],
};

export default function reducer(state = defaultState, action) {
  switch (action.type) {
    /**
     * 新增任务   action 需要一个 text 属性
     */
    case ADD_TASK:
      return {
        ...state,
        tasks: [
          ...state.tasks,
          {
            id: nextId++,
            text: action.text,
            done: false,
          },
        ],
      };

    /**
     * 删除任务 action 需要一个 id 属性
     */
    case DEL_TASK:
      return {
        ...state,
        tasks: state.tasks.filter((task) => task.id !== action.id),
      };

    default:
      return state;
  }
}
